'''
Created on 14 janv. 2012

@author: guillaume
'''

import subprocess, sys
import shlex


def run_command(cmd, args):
  try:
    cmdline = " ".join([ cmd ] + args)
    retcode = subprocess.call(cmdline, shell=True)
    if retcode < 0:
      print >>sys.stderr, "Child terminated with signal: ", -retcode
      return retcode
    else:
      #print >>sys.stderr, "Child returned: ", retcode
      return retcode
  except OSError, e:
    print >>sys.stderr, "Execution failed: ", e
    return -666

def run_command_stdout(cmd, args):
  try:
    cmdline = " ".join([ cmd ] + args)
    args = shlex.split(cmdline)
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    child_stdout = p.stdout
    text = child_stdout.read()
    return  text
  except OSError, e:
    print >>sys.stderr, "In command: ", cmdline
    print >>sys.stderr, "Execution failed: ", e
    raise e

def get_class(cls):
  parts = cls.split('.')
  module = ".".join(parts[:-1])
  m = __import__(module)
  for comp in parts[1:]:
    m = getattr(m, comp)
  return m

